package com.wmlive.hhvideo.heihei.login.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.jakewharton.rxbinding2.widget.RxTextView;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.base.DcBaseActivity;
import com.wmlive.hhvideo.common.observer.DCObserver;
import com.wmlive.hhvideo.heihei.db.datatable.IMMessageDefaultTable;
import com.wmlive.hhvideo.heihei.db.manager.GreenDaoUserDBManager;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageDefaultDBManager;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageUserDBManager;
import com.wmlive.hhvideo.heihei.login.presenter.MobileLoginPresenter;
import com.wmlive.hhvideo.heihei.login.presenter.SmsPresenter;
import com.wmlive.hhvideo.heihei.login.view.MobileLoginView;
import com.wmlive.hhvideo.heihei.login.view.SmsView;
import com.wmlive.hhvideo.heihei.mainhome.activity.MainNewActivity;
import com.wmlive.hhvideo.heihei.websocket.WebSocketServiceManager;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.RegexUtil;
import com.wmlive.hhvideo.utils.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wmlive.hhvideo.R;
import io.reactivex.Observable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Function;

/**
 * Modify by lsq
 */
public class MobileLoginActivity extends DcBaseActivity implements SmsView, MobileLoginView {

    private static final int SMS_CODE_LENGTH = 6;
    private static final long COUNTDOWN_INTERVAL = 60;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.et_sms_code)
    EditText etSmsCode;
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.tv_sms_code)
    TextView tvSmsCode;
    // 倒计时计时器
    private CountDownTimer countDownTimer;
    private SmsPresenter smsPresenter;
    private MobileLoginPresenter mobileLoginPresenter;
    private boolean isReLogin;//是否是重新登录,不是重新登录需要关闭app

    /**
     * @param context
     * @param isReLogin 是否是重新登录
     */
    public static void startMobileLoginActivity(Context context, boolean isReLogin) {
        Intent intent = new Intent(context, MobileLoginActivity.class);
        intent.putExtra("isReLogin", isReLogin);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        super.initData();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        setTitle("登录", false);
        KLog.i("initData");
        isReLogin = getIntent().getBooleanExtra("isReLogin", false);
        mobileLoginControl();
        smsPresenter = new SmsPresenter(this);
        mobileLoginPresenter = new MobileLoginPresenter(this);
        addPresenter(smsPresenter, mobileLoginPresenter);

        etMobile.setFocusable(true);
        etMobile.setFocusableInTouchMode(true);
        etMobile.setSelection(0);
        etMobile.requestFocus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    public void onBackPressed() {
        if (isReLogin) {
            super.onBackPressed();
        } else {
            finish();
            DCApplication.getDCApp().exitApp();
        }
    }

    @Override
    protected void onSingleClick(View v) {

    }


    private void mobileLoginControl() {
        Observable<Boolean> mobileObservable = RxTextView.textChanges(etMobile).map(new Function<CharSequence, Boolean>() {

            @Override
            public Boolean apply(@NonNull CharSequence charSequence) throws Exception {

                return RegexUtil.isValidMobile(charSequence.toString());
            }
        }).skip(1);

        Observable<Boolean> smsObservable = RxTextView.textChanges(etSmsCode).map(new Function<CharSequence, Boolean>() {
            @Override
            public Boolean apply(@NonNull CharSequence charSequence) throws Exception {
                return charSequence.length() == SMS_CODE_LENGTH;
            }
        }).skip(1);


        Observable<Boolean> bothObservable = Observable.combineLatest(mobileObservable, smsObservable, new BiFunction<Boolean, Boolean, Boolean>() {
            @Override
            public Boolean apply(@NonNull Boolean mobileBoolean, @NonNull Boolean smsBoolean) throws Exception {
                return mobileBoolean && smsBoolean;
            }
        });

//        mobileObservable.subscribe(new Consumer<Boolean>() {
//            @Override
//            public void accept(@NonNull Boolean aBoolean) throws Exception {
//
//            }
//        });

        mobileObservable.subscribe(new DCObserver<Boolean>() {
            @Override
            public void onNext(@NonNull Boolean isEnabled) {
                setupSmsButton("验证码", isEnabled);
            }
        });

        bothObservable.subscribe(new DCObserver<Boolean>() {

            @Override
            public void onNext(@NonNull Boolean enable) {
                enableLogin(enable);
            }
        });
    }

    private void enableLogin(Boolean enable) {
        tvLogin.setEnabled(enable);

        tvLogin.setTextColor(getResources().getColor(enable ? R.color.text_color_white : R.color.hh_color_d));
    }

    private void setupSmsButton(String content, Boolean isEnabled) {
        tvSmsCode.setText(content);
        enableSmsBt(isEnabled);
        tvSmsCode.setTextColor(getResources().getColor(isEnabled ? R.color.text_color_white : R.color.hh_color_d));
    }

    private void enableSmsBt(Boolean isEnabled) {
        if (!isEnabled) {
            if (countDownTimer != null) {
                countDownTimer.cancel();
            }
        }
        tvSmsCode.setEnabled(isEnabled);

    }

    /**
     * 倒计时方法
     * 计时步长:1s
     */
    private void startCountDownTimer(final long time) {
        countDownTimer = new CountDownTimer(time * 1000, 1000) {

            public void onTick(long millisUntilFinished) {
                if (tvSmsCode != null) {
                    tvSmsCode.setText(millisUntilFinished / 1000 + "s");
                    tvSmsCode.setTextColor(getResources().getColor(R.color.hh_color_d));
                }
            }

            public void onFinish() {
                setupSmsButton("重新获取", true);
            }
        };
        countDownTimer.start();
    }

    private void stopCountDownTimer() {
        if (null != countDownTimer) {
            countDownTimer.cancel();
//            tvSmsCode.setText("重新获取");
        }
//        enableSmsBt(true);
    }


    public static Intent getCallingIntent(Activity activity) {
        Intent intent = new Intent(activity, MobileLoginActivity.class);
        return intent;
    }


    @OnClick(R.id.tv_sms_code)
    void onSendSmsCodeClick() {
        enableSmsBt(false);
        startCountDownTimer(COUNTDOWN_INTERVAL);
        smsPresenter.sendSmsCode(etMobile.getText().toString());
        loading();
    }

    @OnClick(R.id.tv_login)
    void onLoginClick() {
        mobileLoginPresenter.mobileLogin(etMobile.getText().toString(), etSmsCode.getText().toString());
        loading();
    }

    @Override
    public void handleSmsSucceed() {
//        stopCountDownTimer();
        ToastUtil.showToast(R.string.sms_code_send_succeed);
        dismissLoad();

        etSmsCode.setFocusable(true);
        etSmsCode.setFocusableInTouchMode(true);
        etSmsCode.setSelection(0);
        etSmsCode.requestFocus();
    }

    @Override
    public void handleSmsFailure(String msg) {
//        stopCountDownTimer();
        ToastUtil.showToast(msg);
        dismissLoad();
    }

    @Override
    public void handleSmsError() {
//        stopCountDownTimer();
        ToastUtil.showToast(R.string.net_error);
        dismissLoad();
    }

    @Override
    public void handleLoginSucceed() {
//        Navigator.getInstance().navigateToMain(this);
        dismissLoad();
        if (isReLogin) {
            finish();
        } else {
            MainNewActivity.startActivity(this);
        }
    }

    @Override
    public void handleLoginComplete() {
        //登录成功，重新启动websocket 服务
        WebSocketServiceManager.getInstance(DCApplication.getDCApp()).reStartWebSocketService();
        //切换数据库
        IMMessageUserDBManager.switchUserDBManager(DCApplication.getDCApp());
        //删除临时数据库
        IMMessageDefaultDBManager.getInstance(DCApplication.getDCApp()).delImDefaultEntryAll();
        finish();
        dismissLoad();
    }

    @Override
    public void handleLoginFailure(String msg) {
        ToastUtil.showToast(msg);
        dismissLoad();
    }

    @Override
    public void handleLoginError() {
        ToastUtil.showToast(R.string.net_error);
        dismissLoad();
    }
}
